# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

from coin.base.book import BookBuilderBase
from coin.exchange.bithumb.kr_rest.product import BithumbProduct


class BookEntry(object):
  def __init__(self, price, qty):
    self.price = float(price)
    self.qty = float(qty)


class BookBuilder(BookBuilderBase):
  ProductType = BithumbProduct

  def __init__(self, native_symbol, book_builder_observer=None):
    super().__init__("Bithumb", native_symbol, book_builder_observer=book_builder_observer)

  def update(self, bids: list, asks: list):
    self._bid_price_map.clear()
    for data in bids:
      price = float(data['price'])
      qty = float(data['quantity'])
      self._insert_bid(price, qty)

    self._ask_price_map.clear()
    for data in asks:
      price = float(data['price'])
      qty = float(data['quantity'])
      self._insert_ask(price, qty)

  def _insert_bid(self, price, qty):
    assert price > 0, price
    assert qty >= 0, qty
    if qty == 0.:
      return
    entry = BookEntry(price, qty)
    self._bid_price_map[price] = entry

  def _insert_ask(self, price, qty):
    assert price > 0, price
    assert qty >= 0, qty
    if qty == 0.:
      return
    entry = BookEntry(price, qty)
    self._ask_price_map[price] = entry

  def _delete_bid(self, price):
    if price in self._bid_price_map:
      del self._bid_price_map[price]

  def _delete_ask(self, price):
    if price in self._ask_price_map:
      del self._ask_price_map[price]

  def update_bid(self, price, qty):
    if qty > 0:
      self._insert_bid(price, qty)
    else:
      self._delete_bid(price)

  def update_ask(self, price, qty):
    if qty > 0:
      self._insert_ask(price, qty)
    else:
      self._delete_ask(price)
